//
//  DXMLPeriodObject.m
//  DerbyStatter
//
//  Created by glenn andreas on 1/6/14.
//  Copyright (c) 2014 glenn andreas. All rights reserved.
//

#import "DXMLPeriodObject.h"
#import "DXMLJamObject.h"
#import "DXMLSkaterEventObject.h"
#import "DXMLBoutObject.h"

@implementation DXMLPeriodObject
DXMLINTATTR(number, Number)
DXMLCHILDRENATTR(jams, Jams, DXMLJamObject)
- (NSInteger) numberOfJams
{
    return [self numberOfChildrenOfClass:[DXMLJamObject class]];
}
- (DXMLJamObject *)jamAtIndex: (NSInteger) index
{
    return [self childOfClass:[DXMLJamObject class] atIndex:index];
}
- (DXMLJamObject *)jamAtIndex: (NSInteger) index source: (DXMLEventSource) source
{
    DXMLJamObject *retval = [self jamAtIndex:index];
    if (retval)
        return retval;
    retval = [self childOfClass:[DXMLJamObject class] atIndex:index source:source];
    __block NSInteger lastJam = 0;
    [self enumerateJams:^(DXMLJamObject *jam, BOOL *stop) {
        if (jam.number != NSNotFound)
            lastJam = jam.number;
        else {
            lastJam++;
            jam.number = lastJam;
        }
    }];
    return retval;
}
- (void) enumerateJams: (void (^)(DXMLJamObject *jam, BOOL *stop)) block
{
    [self enumerateChildren:(void (^)(DXMLEventObject *child, BOOL *stop))block ofClass:[DXMLJamObject class]];
}

- (NSInteger) periodTotalForTeam: (DXMLTeamObject *) team upToJam: (NSInteger) jamNumber
{
    __block NSInteger retval = 0;
    __block NSInteger jn = 1;
    [self enumerateJams:^(DXMLJamObject *jam, BOOL *stop) {
        retval += [jam score:team];
        if (jn >= jamNumber)
            *stop = YES;
        jn++;
    }];
    return retval;
}

- (DXMLBoutObject *) bout
{
    return [self enclosingParentOfClass:[DXMLBoutObject class]];
}


@end
